import Controller from "./Controller";
import {Request,Response} from 'express';
import Config from '../Config'
import Fs from 'fs-extra'
import admZip from 'adm-zip'
import { exec } from 'child_process';
import { join as path_join } from 'path'
import md5 from 'md5'

class Tpl extends Controller
{
    constructor(req?:Request,res?:Response) {
        super(req,res);
    }

    /**
     * 新增模板
     */
    async add() {
        try {
            const data:any = await this.first('tpl',{
                name: this.HD.name
            })
            if(data) {
                throw new Error("模板名称已存在");
            }
            const result = await this.insert('tpl',{
                name: this.HD.name
            })
            this.response(200,{
                id: result
            })
        }catch(error:any) {
            this.response(error.code?error.code:402,[],error.message)
        }
    }

    /**
     * 获取列表
     */
    async get() {
        try {
            const data:any = await this.all('tpl')
            this.createAttachmentSynlink()
            for(let i=0;i<data.length;i++) {
                data[i].url = this.getPorjectThumbUrl(data[i].id)
            }
            this.response(200,data) 
        }catch(error:any) {
            this.response(error.code?error.code:402,[],error.message)
        }
    }

    /**
     * 创建系统attachment软链接
     */
    createAttachmentSynlink() {
        const target = path_join(Config.root_dir,"public","attachment");
        if(Fs.pathExistsSync(Config.attachment_dir) && !Fs.pathExistsSync(target)) {
            Fs.symlinkSync(Config.attachment_dir,target,'junction');
        }
    }

    /**
     * 后去项目的
     */
    getPorjectThumbUrl(id:number) :string|Boolean {
        let url:any = false;
        const project_thumb_path = path_join(Config.attachment_dir,"images","project_thumb",`${id}.png`)
        if(Fs.pathExistsSync(project_thumb_path)) {
            url = `${Config.domian}/attachment/images/project_thumb/${id}.png?time=${new Date().getTime()}`
        }
        return url;
    }

    /**
     * 生成项目封面图片
     */
    async createThumb(Cache:any) {
        const tpl_id = Cache.get("tpl_id");
        const attachment_images = path_join(Config.attachment_dir,'images','project_thumb');
        if(!Fs.pathExistsSync(attachment_images)) {
            Fs.mkdirpSync(attachment_images); 
        }

        const filename = path_join(attachment_images,`${tpl_id}.png`)
        const base64 = this.req!.body.dataUrl;

        Fs.writeFileSync(filename,base64,'base64');

        this.response(200)
    }

    /**
     * 删除模板项目
     */
    async remove() 
    {
        const tpl_id = this.HD.tpl_id;
        // 先获取到项目目录
        const Tpl = await this.first("tpl",{id:tpl_id}) as { dir:string };
        // 删除id
        await this.delete("tpl",{id:tpl_id})
        // 删除目录
        Fs.removeSync(path_join(Config.data_dir,Tpl.dir));
        this.response(200);
    }
}

export default Tpl;